const kitchenService = require('../../services/kitchenService');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    kitchenId: '',
    mode: 'create', // create 或 edit
    name: '',
    description: '',
    image: '',
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const mode = options.mode || 'create';
    
    this.setData({
      mode
    });
    
    if (mode === 'edit' && options.id) {
      this.setData({
        kitchenId: options.id
      });
      this.loadKitchenData(options.id);
    }
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: mode === 'create' ? '创建厨房' : '编辑厨房'
    });
  },

  /**
   * 加载厨房数据
   */
  async loadKitchenData(id) {
    this.setData({ loading: true });
    
    try {
      const kitchen = await kitchenService.getKitchenById(id);
      
      if (kitchen) {
        console.log('加载到厨房数据:', kitchen);
        this.setData({
          name: kitchen.name || '',
          description: kitchen.description || '',
          image: kitchen.image || '/imgs/chef-hat.svg',
          loading: false
        });
      } else {
        wx.showToast({
          title: '未找到厨房数据',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载厨房数据失败', error);
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  /**
   * 选择图片
   */
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          image: tempFilePath
        });
        
        // 上传图片到云存储
        this.uploadImage(tempFilePath);
      }
    });
  },
  
  /**
   * 上传图片到云存储
   */
  async uploadImage(filePath) {
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    
    try {
      const timestamp = new Date().getTime();
      const cloudPath = `kitchen/${timestamp}.jpg`;
      
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: filePath
      });
      
      console.log('图片上传成功:', uploadResult);
      
      this.setData({
        image: uploadResult.fileID
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '图片上传成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('上传图片失败', error);
      wx.hideLoading();
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      });
    }
  },

  /**
   * 保存厨房信息
   */
  async saveKitchen() {
    const { kitchenId, name, description, image, mode } = this.data;
    
    // 表单验证
    if (!name.trim()) {
      wx.showToast({
        title: '请输入厨房名称',
        icon: 'none'
      });
      return;
    }
    
    // 准备厨房数据
    const kitchenData = {
      name: name.trim(),
      description: description.trim(),
      image: image
    };
    
    // 如果是编辑模式，添加ID
    if (mode === 'edit') {
      kitchenData._id = kitchenId;
    }
    
    console.log('准备保存厨房数据:', kitchenData);
    
    wx.showLoading({
      title: '保存中...',
      mask: true
    });
    
    try {
      const success = await kitchenService.saveKitchen(kitchenData);
      wx.hideLoading();
      
      if (success) {
        console.log('厨房保存成功');
        
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            setTimeout(() => {
              // 通知列表页面刷新数据
              const eventChannel = this.getOpenerEventChannel();
              if (eventChannel && eventChannel.emit) {
                eventChannel.emit('kitchenUpdated', { success: true });
              }
              
              wx.navigateBack();
            }, 1500);
          }
        });
      } else {
        console.error('保存厨房失败');
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('保存厨房出错', error);
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  /**
   * 删除厨房
   */
  deleteKitchen() {
    const { kitchenId } = this.data;
    
    if (!kitchenId) {
      wx.showToast({
        title: '无法删除',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个厨房吗？厨房中的所有菜品将被一并删除，此操作不可恢复。',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
            mask: true
          });
          
          try {
            const success = await kitchenService.deleteKitchen(kitchenId);
            wx.hideLoading();
            
            if (success) {
              console.log('厨房删除成功');
              
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1500,
                success: () => {
                  setTimeout(() => {
                    // 通知列表页面刷新数据
                    const eventChannel = this.getOpenerEventChannel();
                    if (eventChannel && eventChannel.emit) {
                      eventChannel.emit('kitchenUpdated', { success: true });
                    }
                    
                    wx.navigateBack();
                  }, 1500);
                }
              });
            } else {
              console.error('删除厨房失败');
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除厨房出错', error);
            wx.hideLoading();
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },
  
  /**
   * 处理输入字段变化
   */
  onNameInput(e) {
    this.setData({
      name: e.detail.value
    });
  },
  
  onDescriptionInput(e) {
    this.setData({
      description: e.detail.value
    });
  }
}) 